package com.example.treehole.ui.page.myself

import androidx.lifecycle.ViewModel
import com.example.treehole.service.DataRepository
import com.example.treehole.ui.model.Comment
import com.example.treehole.ui.model.PostInfo
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update

class MySelfViewModel : ViewModel() {
    private val _myPostLists = MutableStateFlow<List<PostInfo>>(emptyList())
    val myPostList: StateFlow<List<PostInfo>> = _myPostLists
    private val _myPostPage = MutableStateFlow<Int>(0)
    val myPostPage: StateFlow<Int> = _myPostPage

    private val _myCommentLists = MutableStateFlow<List<Comment>>(emptyList())
    val myCommentList: StateFlow<List<Comment>> = _myCommentLists
    private val _myCommentPage = MutableStateFlow<Int>(0)
    val myCommentPage: StateFlow<Int> = _myCommentPage

    fun updateMyPostList(posts: List<PostInfo>) {
        _myPostLists.value = posts
    }

    fun addMyPostList(posts: List<PostInfo>) {
        _myPostLists.update { current ->
            current + posts
        }
    }

    suspend fun refreshMyPostList(
        jwlToken: String,
        userId: Int,
    ) {
        val res = DataRepository.getMyPosts(jwlToken, userId, 0)
        res?.let {
            updateMyPostList(it)
            _myPostPage.value = 0
        }
    }

    suspend fun getMoreMyPostList(
        jwlToken: String,
        userId: Int
    ) {
        val res = DataRepository.getMyPosts(jwlToken, userId, myPostPage.value + 1)
//        val res = postList
        res?.let {
            if (it.isNotEmpty()) {
                addMyPostList(it)
                _myPostPage.value++
            } else {
                _myPostPage.value = -2 // 表示没有更多帖子可以获取
            }
        }
    }

    fun updateMyCommentList(comments: List<Comment>) {
        _myCommentLists.value = comments
    }

    fun addMyCommentList(comments: List<Comment>) {
        _myCommentLists.update { current ->
            current + comments
        }
    }

    suspend fun refreshMyCommentList(
        jwlToken: String,
        userId: Int,
    ) {
        val res = DataRepository.getMyComments(jwlToken, userId,  0)
        res?.let {
            updateMyCommentList(it)
            _myCommentPage.value = 0
        }
    }

    suspend fun getMoreMyCommentList(
        jwlToken: String,
        userId: Int
    ) {
        val res = DataRepository.getMyComments(
            jwlToken,
            userId,
            myCommentPage.value + 1
        )
//        val res = postList
        res?.let {
            if (it.isNotEmpty()) {
                addMyCommentList(it)
                _myCommentPage.value++
            } else {
                _myCommentPage.value = -2 // 表示没有更多评论可以获取
            }
        }
    }


}